<template>
  <div class="order-container">
    <div class="order-header">
      <h1>订单管理</h1>
      <div class="header-actions">
        <el-button @click="exportOrders" type="primary" plain>
          <el-icon><Download /></el-icon>
          导出订单
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="16" class="stats-cards">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon pending">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ orderStats.todayStats?.orders || 0 }}</div>
              <div class="stat-label">今日订单</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon total">
              <el-icon><ShoppingCart /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ totalOrders }}</div>
              <div class="stat-label">总订单数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon sales">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ (orderStats.todayStats?.sales || 0).toFixed(2) }}</div>
              <div class="stat-label">今日销售额</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon amount">
              <el-icon><Wallet /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ totalSales.toFixed(2) }}</div>
              <div class="stat-label">总销售额</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索筛选 -->
    <el-card class="filter-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="订单号">
          <el-input
            v-model="searchForm.order_number"
            placeholder="请输入订单号"
            clearable
            style="width: 200px;"
          />
        </el-form-item>
        <el-form-item label="用户">
          <el-input
            v-model="searchForm.customer"
            placeholder="请输入用户名称"
            clearable
            style="width: 200px;"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="全部状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="待付款" value="pending" />
            <el-option label="已付款" value="paid" />
            <el-option label="已发货" value="shipped" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
            <el-option label="已退款" value="refunded" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单表格 -->
    <el-card>
      <div class="table-actions">
        <el-button 
          v-if="selectedOrders.length > 0"
          @click="handleBulkAction('shipped')"
          type="success"
          size="small"
        >
          批量发货
        </el-button>
        <el-button 
          v-if="selectedOrders.length > 0"
          @click="handleBulkAction('completed')"
          type="primary"
          size="small"
        >
          批量完成
        </el-button>
      </div>

      <el-table 
        :data="orderList" 
        v-loading="loading" 
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="order_number" label="订单号" width="200">
          <template #default="{ row }">
            <div class="order-number">
              {{ row.order_number }}
            </div>
            <div class="order-time">
              {{ formatDate(row.created_at) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="用户信息" width="180">
          <template #default="{ row }">
            <div class="customer-info">
              <div class="customer-name">{{ row.audience?.audience_name || '未知用户' }}</div>
              <div class="customer-contact">{{ row.audience?.email || '无邮箱' }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品信息" min-width="200">
          <template #default="{ row }">
            <div class="product-list">
              <div 
                v-for="item in row.items" 
                :key="item.order_item_id"
                class="product-item"
              >
                <el-image
                  v-if="item.product?.cover_image"
                  :src="getFullImageUrl(item.product.cover_image)"
                  fit="cover"
                  class="product-image"
                />
                <div class="product-details">
                  <div class="product-name">{{ item.product_name }}</div>
                  <div class="product-price">¥{{ item.product_price }} × {{ item.quantity }}</div>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="total_amount" label="金额" width="120">
          <template #default="{ row }">
            <div class="amount">¥{{ row.total_amount }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="收货信息" width="180">
          <template #default="{ row }">
            <div class="shipping-info">
              <div class="recipient">{{ row.recipient_name }}</div>
              <div class="phone">{{ row.recipient_phone }}</div>
              <div class="address">{{ row.shipping_address }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              size="small" 
              @click="handleViewDetail(row)"
              type="primary"
            >
              详情
            </el-button>
            <el-button 
              v-if="row.status === 'paid'"
              size="small" 
              @click="handleUpdateStatus(row, 'shipped')"
              type="success"
            >
              发货
            </el-button>
            <el-button 
              v-if="row.status === 'shipped'"
              size="small" 
              @click="handleUpdateStatus(row, 'completed')"
              type="warning"
            >
              完成
            </el-button>
            <el-button 
              v-if="['pending', 'paid'].includes(row.status)"
              size="small" 
              @click="handleUpdateStatus(row, 'cancelled')"
              type="danger"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog 
      v-model="showDetailDialog" 
      title="订单详情" 
      width="800px"
      @close="showDetailDialog = false"
    >
      <div v-if="currentOrder" class="order-detail-simple">
        <el-descriptions title="订单信息" :column="2" border>
          <el-descriptions-item label="订单号">{{ currentOrder.order_number }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(currentOrder.status)">
              {{ getStatusText(currentOrder.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="订单金额">¥{{ currentOrder.total_amount }}</el-descriptions-item>
          <el-descriptions-item label="下单时间">{{ formatDate(currentOrder.created_at) }}</el-descriptions-item>
        </el-descriptions>

        <el-descriptions title="收货信息" :column="1" border style="margin-top: 20px;">
          <el-descriptions-item label="收货人">{{ currentOrder.recipient_name }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentOrder.recipient_phone }}</el-descriptions-item>
          <el-descriptions-item label="收货地址">{{ currentOrder.shipping_address }}</el-descriptions-item>
        </el-descriptions>

        <el-table :data="currentOrder.items" style="margin-top: 20px;">
          <el-table-column label="商品名称" prop="product_name" />
          <el-table-column label="单价" prop="product_price" width="100">
            <template #default="{ row }">¥{{ row.product_price }}</template>
          </el-table-column>
          <el-table-column label="数量" prop="quantity" width="80" />
          <el-table-column label="小计" prop="subtotal" width="100">
            <template #default="{ row }">¥{{ row.subtotal }}</template>
          </el-table-column>
        </el-table>

        <div style="margin-top: 20px; text-align: center;">
          <el-button 
            v-if="currentOrder.status === 'paid'"
            @click="handleUpdateStatus(currentOrder, 'shipped')"
            type="success"
          >
            确认发货
          </el-button>
          <el-button 
            v-if="currentOrder.status === 'shipped'"
            @click="handleUpdateStatus(currentOrder, 'completed')"
            type="primary"
          >
            确认完成
          </el-button>
          <el-button 
            v-if="['pending', 'paid'].includes(currentOrder.status)"
            @click="handleUpdateStatus(currentOrder, 'cancelled')"
            type="danger"
          >
            取消订单
          </el-button>
          <el-button @click="showDetailDialog = false">关闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Download, 
  Clock, 
  ShoppingCart, 
  Money, 
  Wallet 
} from '@element-plus/icons-vue'
import { adminAPI } from '../../api/admin'

interface Order {
  order_id: number
  order_number: string
  total_amount: number
  status: string
  shipping_address: string
  recipient_name: string
  recipient_phone: string
  note: string
  created_at: string
  paid_at: string
  completed_at: string
  audience?: {
    audience_name: string
    email: string
    phone: string
  }
  items: OrderItem[]
}

interface OrderItem {
  order_item_id: number
  product_id: number
  product_name: string
  product_price: number
  quantity: number
  subtotal: number
  product?: {
    cover_image: string
    anchor?: {
      anchor_name: string
    }
  }
}

// 响应式数据
const loading = ref(false)
const showDetailDialog = ref(false)
const selectedOrders = ref<Order[]>([])
const currentOrder = ref<Order | null>(null)

const orderList = ref<Order[]>([])
const orderStats = ref({
  statusStats: {},
  todayStats: {},
  totalStats: {}
})

const searchForm = reactive({
  order_number: '',
  customer: '',
  status: '',
  dateRange: []
})

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 计算属性
const totalOrders = computed(() => {
  return orderStats.value.totalStats?.orders || 0
})

const totalSales = computed(() => {
  return orderStats.value.totalStats?.sales || 0
})

// 加载订单列表
const loadOrders = async () => {
  try {
    loading.value = true
    console.log('📦 加载订单列表...')
    
    const params: any = {
      page: pagination.current,
      limit: pagination.pageSize
    }
    
    if (searchForm.status) params.status = searchForm.status
    if (searchForm.order_number) params.order_number = searchForm.order_number
    if (searchForm.customer) params.customer = searchForm.customer
    
    // 添加日期筛选
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.start_date = searchForm.dateRange[0]
      params.end_date = searchForm.dateRange[1]
    }
    
    const response = await adminAPI.getOrders(params)
    
    console.log('📦 订单API响应:', response)
    
    let success, data
    
    if (response.success !== undefined) {
      success = response.success
      data = response.data
    } else if (response.data && response.data.success !== undefined) {
      success = response.data.success
      data = response.data.data
    } else {
      success = true
      data = response.data || response
    }
    
    if (success) {
      orderList.value = data?.orders || data || []
      pagination.total = data?.pagination?.total || data?.total || orderList.value.length
      console.log('✅ 订单列表加载成功，数量:', orderList.value.length)
    } else {
      throw new Error('数据加载失败')
    }
    
  } catch (error: any) {
    console.error('❌ 加载订单列表失败:', error)
    ElMessage.error('加载订单列表失败: ' + (error.message || '网络错误'))
    
    // 使用模拟数据测试
    orderList.value = generateMockOrders()
    pagination.total = orderList.value.length
    ElMessage.info('使用模拟数据展示')
  } finally {
    loading.value = false
  }
}

// 生成模拟订单数据
const generateMockOrders = (): Order[] => {
  return [
    {
      order_id: 1,
      order_number: 'ORD202401010001',
      total_amount: 199.99,
      status: 'paid',
      shipping_address: '北京市朝阳区xxx街道',
      recipient_name: '张三',
      recipient_phone: '13800138000',
      note: '请尽快发货',
      created_at: new Date().toISOString(),
      paid_at: new Date().toISOString(),
      completed_at: '',
      audience: {
        audience_name: '张三',
        email: 'zhangsan@example.com',
        phone: '13800138000'
      },
      items: [
        {
          order_item_id: 1,
          product_id: 1,
          product_name: '测试商品1',
          product_price: 99.99,
          quantity: 2,
          subtotal: 199.98,
          product: {
            cover_image: '/uploads/products/test1.jpg'
          }
        }
      ]
    },
    {
      order_id: 2,
      order_number: 'ORD202401010002',
      total_amount: 299.99,
      status: 'pending',
      shipping_address: '上海市浦东新区xxx路',
      recipient_name: '李四',
      recipient_phone: '13900139000',
      note: '',
      created_at: new Date().toISOString(),
      paid_at: '',
      completed_at: '',
      audience: {
        audience_name: '李四',
        email: 'lisi@example.com',
        phone: '13900139000'
      },
      items: [
        {
          order_item_id: 2,
          product_id: 2,
          product_name: '测试商品2',
          product_price: 299.99,
          quantity: 1,
          subtotal: 299.99,
          product: {
            cover_image: '/uploads/products/test2.jpg'
          }
        }
      ]
    }
  ]
}

// 加载订单统计 - 修复错误处理
const loadOrderStats = async () => {
  try {
    console.log('📊 开始加载订单统计...')
    
    const response = await adminAPI.getOrderStats()
    
    console.log('📊 订单统计API响应:', response)
    
    let success, data
    
    if (response.success !== undefined) {
      success = response.success
      data = response.data
    } else if (response.data && response.data.success !== undefined) {
      success = response.data.success
      data = response.data.data
    } else {
      success = true
      data = response.data || response
    }
    
    if (success) {
      // 确保数据结构完整
      orderStats.value = {
        statusStats: data.statusStats || {},
        todayStats: data.todayStats || { orders: 0, sales: 0 },
        totalStats: data.totalStats || { orders: 0, sales: 0 }
      }
      console.log('✅ 订单统计加载成功:', orderStats.value)
    } else {
      console.warn('⚠️ 订单统计API返回失败:', response.message)
      useMockOrderStats()
    }
  } catch (error: any) {
    console.error('❌ 加载订单统计失败:', error)
    
    // 根据错误类型提供更具体的提示
    if (error.response?.status === 404) {
      console.warn('📊 订单统计API端点不存在，使用模拟数据')
    } else if (error.response?.status === 500) {
      console.warn('📊 服务器内部错误，使用模拟数据')
    } else {
      console.warn('📊 网络错误，使用模拟数据')
    }
    
    useMockOrderStats()
  }
}

// 提取模拟数据到独立函数
const useMockOrderStats = () => {
  orderStats.value = {
    statusStats: {
      pending: { order_count: 5, total_amount: 1500 },
      paid: { order_count: 10, total_amount: 3000 },
      shipped: { order_count: 3, total_amount: 900 },
      completed: { order_count: 20, total_amount: 6000 },
      cancelled: { order_count: 2, total_amount: 400 },
      refunded: { order_count: 1, total_amount: 200 }
    },
    todayStats: {
      orders: 2,
      sales: 499.98
    },
    totalStats: {
      orders: 41, // 5+10+3+20+2+1
      sales: 12000 // 1500+3000+900+6000+400+200
    }
  }
  console.log('📊 使用模拟订单统计数据')
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadOrders()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    order_number: '',
    customer: '',
    status: '',
    dateRange: []
  })
  pagination.current = 1
  loadOrders()
}

// 查看订单详情
const handleViewDetail = async (order: Order) => {
  try {
    console.log('🔍 查看订单详情:', order.order_id)
    
    // 直接使用当前订单数据，避免额外API调用
    currentOrder.value = order
    showDetailDialog.value = true
    
    // 如果需要完整数据，可以调用API
    // const response = await adminAPI.getOrderById(order.order_id)
    // ... API调用逻辑
  } catch (error: any) {
    console.error('加载订单详情失败:', error)
    ElMessage.error('加载订单详情失败: ' + (error.message || '网络错误'))
  }
}

// 更新订单状态
const handleUpdateStatus = async (order: Order, newStatus: string) => {
  try {
    const actionText = getStatusActionText(newStatus)
    
    await ElMessageBox.confirm(
      `确定要将订单 "${order.order_number}" ${actionText}吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    console.log('🔄 更新订单状态:', order.order_id, newStatus)
    
    // 模拟API调用
    const response = await adminAPI.updateOrderStatus(order.order_id, newStatus)
    
    let success, message
    
    if (response.success !== undefined) {
      success = response.success
      message = response.message
    } else if (response.data && response.data.success !== undefined) {
      success = response.data.success
      message = response.data.message
    } else {
      success = true
      message = '状态更新成功'
    }
    
    if (success) {
      ElMessage.success(`${actionText}成功`)
      // 更新本地状态
      order.status = newStatus
      showDetailDialog.value = false
      loadOrders()
      loadOrderStats()
    } else {
      throw new Error(message || `${actionText}失败`)
    }
    
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('更新订单状态失败:', error)
      ElMessage.error('操作失败: ' + (error.message || '网络错误'))
    }
  }
}

// 批量操作
const handleBulkAction = async (action: string) => {
  try {
    const actionText = getStatusActionText(action)
    const orderIds = selectedOrders.value.map(order => order.order_id)
    
    if (orderIds.length === 0) {
      ElMessage.warning('请先选择订单')
      return
    }
    
    await ElMessageBox.confirm(
      `确定要批量${actionText} ${orderIds.length} 个订单吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    console.log('🔄 批量操作:', action, orderIds)
    
    // 模拟批量操作
    for (const order of selectedOrders.value) {
      order.status = action
    }
    
    ElMessage.success(`批量${actionText}成功`)
    selectedOrders.value = []
    
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('批量操作失败:', error)
      ElMessage.error('操作失败: ' + (error.message || '网络错误'))
    }
  }
}

// 选择改变
const handleSelectionChange = (selection: Order[]) => {
  selectedOrders.value = selection
}

// 状态更新后处理
const handleStatusUpdated = () => {
  showDetailDialog.value = false
  loadOrders()
  loadOrderStats()
}

// 导出订单
const exportOrders = () => {
  ElMessage.info('导出功能开发中...')
}

// 工具函数
const getStatusType = (status: string) => {
  const types: { [key: string]: string } = {
    pending: 'warning',
    paid: 'success',
    shipped: 'info',
    completed: 'success',
    cancelled: 'danger',
    refunded: 'info'
  }
  return types[status] || 'info'  // 添加默认值
}

const getStatusText = (status: string) => {
  const texts: { [key: string]: string } = {
    pending: '待付款',
    paid: '已付款',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消',
    refunded: '已退款'
  }
  return texts[status] || status
}

const getStatusActionText = (status: string) => {
  const texts: { [key: string]: string } = {
    shipped: '发货',
    completed: '完成',
    cancelled: '取消'
  }
  return texts[status] || '操作'
}

const getFullImageUrl = (url: string) => {
  if (url.startsWith('http')) {
    return url
  }
  return `http://localhost:3000${url}`
}

const formatDate = (date: string | Date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.current = 1
  loadOrders()
}

const handleCurrentChange = (page: number) => {
  pagination.current = page
  loadOrders()
}

onMounted(() => {
  console.log('🚀 订单管理页面加载')
  loadOrders()
  loadOrderStats()
})
</script>

<style scoped>
.order-container {
  padding: 20px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 100px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.stat-icon.pending { background: #e6a23c; }
.stat-icon.total { background: #409eff; }
.stat-icon.sales { background: #67c23a; }
.stat-icon.amount { background: #f56c6c; }

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}

.filter-card {
  margin-bottom: 20px;
}

.table-actions {
  margin-bottom: 16px;
}

.order-number {
  font-weight: 600;
  color: #303133;
}

.order-time {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.customer-info {
  line-height: 1.4;
}

.customer-name {
  font-weight: 500;
  color: #303133;
}

.customer-contact {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}

.product-list {
  max-height: 120px;
  overflow-y: auto;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 4px 0;
  border-bottom: 1px solid #f0f0f0;
}

.product-item:last-child {
  border-bottom: none;
}

.product-image {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  margin-right: 8px;
}

.product-details {
  flex: 1;
}

.product-name {
  font-size: 13px;
  color: #303133;
  margin-bottom: 2px;
}

.product-price {
  font-size: 12px;
  color: #909399;
}

.amount {
  font-weight: 600;
  color: #f56c6c;
}

.shipping-info {
  line-height: 1.4;
  font-size: 13px;
}

.recipient {
  font-weight: 500;
}

.phone {
  color: #606266;
  margin: 2px 0;
}

.address {
  color: #909399;
  font-size: 12px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.order-detail-simple {
  max-height: 60vh;
  overflow-y: auto;
}
</style>